package com.ccit.springbootlaw.controller;

import com.ccit.springbootlaw.controller.resful.Code;
import com.ccit.springbootlaw.controller.resful.Result;
import com.ccit.springbootlaw.pojo.Comment;
import com.ccit.springbootlaw.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/text-comments")
public class TextCommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 根据文章ID查询所有父评论ID为空的评论及其子评论
     *
     * @param articleId 文章ID
     * @return 返回包含父子关系的评论列表，状态码为20041（GET_OK）
     */
    @GetMapping("/article/{articleId}")
    public Result getCommentsWithChildrenByArticleId(@PathVariable int articleId) {
        List<Comment> comments = commentService.findRootCommentsByArticleId(articleId);
        List<Comment> textComment = new ArrayList<>();
        for (Comment comment : comments) {
            textComment.add(comment);
            textComment.addAll(findChildren(comment));
        }
        return new Result(Code.GET_OK, textComment, "查询成功");
    }

    public List<Comment> findChildren(Comment comment) {
        List<Comment> ans = new ArrayList<>();
        List<Comment> children = commentService.findByParentId(comment.getId());
        if (children.isEmpty()) {
            return ans;
        } else {
            for (Comment child : children) {
                ans.add(child);
                List<Comment> grandChildren = findChildren(child);
                ans.addAll(grandChildren);
            }
        }
        return ans;
    }
}